package com.itheima.reggie.web.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();// /backend/index.html

        log.info("拦截到请求：{}",requestURI);

        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                //将Swagger及Knife4j相关的静态资源直接放行
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        //2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        //3、如果不需要处理，则直接放行
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        //4-1、判断登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("employee") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("employee"));

            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request,response);
            return;
        }

        //4-2、判断登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }

        log.info("用户未登录");
        //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
    /*package com.itheima.reggie.web.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("登录过滤器......");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        //1.放行应该直接放行的资源
        String paths[] ={//paths是一个数组,里面包含了所有可以直接通过的路径
                "/employee/login",//登出
                "/employee/logout",//退出登录
                "/backend",//管理员静态资源
                "/front",//客户端静态资源
                "/common",
                "/user/sendMsg",   //用户登录
                "/user/login",
                //将Swagger及Knife4j相关的静态资源直接放行
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        String url =req.getRequestURI().toString();
        //url表示命令行获得到的路径
        for (String path : paths){//使用增强for循环获取paths数组中的每一个可以通过的路径
            if (url.contains(path)){//如果url中包含paths中任意一个路径则允许通过
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }

        //2.判断用户是否登录(session)
        HttpSession session =req.getSession();//查询历时记录,是否有session,如果不为null则直接放行
        Object emp = session.getAttribute("employee");//一定要写前面controller内存过的数据(第六步)

        if (emp != null){
            //登录过了;直接放行
            Long empId = (Long) req.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);


            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //移动端用户登录
        if (req.getSession().getAttribute("user") !=null){
            Long em = (Long) req.getSession().getAttribute("user");
            BaseContext.setCurrentId(em);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //3.资源不直接放行,用户未登录,访问失败,前端跳转到登陆页面
        //手动返回R对象的json字符串给前端ajax(响应拦截器:mag=NOTLOGIN,code=0)
        servletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }
}
*/
}
